package com.ruoyi.common.config;

import lombok.Data;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Data
public class MqttPusher  {



    private static final Logger log = LoggerFactory.getLogger(MqttPusher.class);


    public static MqttClient client;

    public static MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();



    public static void push(MqttClientConfig mqttClientConfig,String topic,String data) throws Exception{

        MemoryPersistence persistence = new MemoryPersistence();
        System.out.println("开始推送消息");
        System.out.println(mqttClientConfig.getServerUrl());
        client = new MqttClient(mqttClientConfig.getServerUrl(), mqttClientConfig.getClientId(), persistence);

        mqttConnectOptions.setUserName(mqttClientConfig.getUsername());
        mqttConnectOptions.setPassword(mqttClientConfig.getPassword().toCharArray());
        // 保留会话
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setAutomaticReconnect(true);
        client.connect(mqttConnectOptions);

        client.publish(topic, data.getBytes(), 0, false);

        client.disconnect();

    }

    public static void pushHex(MqttClientConfig mqttClientConfig,String topic,byte[] data) throws Exception{

        MemoryPersistence persistence = new MemoryPersistence();
        System.out.println("开始推送消息");
        System.out.println(mqttClientConfig.getServerUrl());
        client = new MqttClient(mqttClientConfig.getServerUrl(), mqttClientConfig.getClientId(), persistence);

        mqttConnectOptions.setUserName(mqttClientConfig.getUsername());
        mqttConnectOptions.setPassword(mqttClientConfig.getPassword().toCharArray());
        // 保留会话
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setAutomaticReconnect(true);
        client.connect(mqttConnectOptions);

        client.publish(topic, data, 0, false);

        client.disconnect();

    }

}
